//
//  TWCircleLayout.m
//  自定义布局
//
//  Created by 耐克了解了 on 17/4/17.
//  Copyright © 2017年 耐克了解了. All rights reserved.
//

#import "TWCircleLayout.h"

@interface TWCircleLayout ()

@property (nonatomic,strong) NSMutableArray *attrsArray;

@end

@implementation TWCircleLayout

-(NSMutableArray *)attrsArray
{
    if (!_attrsArray) {
        _attrsArray = [NSMutableArray array];
        
    }
    return _attrsArray;
}


- (void)prepareLayout
{
    [super prepareLayout];
    
    [self.attrsArray removeAllObjects];
    
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
//    CGFloat radius = 100;
//    CGFloat OpointX = self.collectionView.frame.size.width *0.5;
//    CGFloat OpointY = self.collectionView.frame.size.height *0.5;
    for (NSInteger i = 0; i < count; i++) {
        
       NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
//        UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
//        
//        attrs.size = CGSizeMake(75, 75);
//        CGFloat angle = (2*M_PI / count)*i;
//        
//        CGFloat centerX = OpointX + radius * sin(angle);
//        CGFloat centerY = OpointY + radius * cos(angle);
//        attrs.center = CGPointMake(centerX, centerY);
        
        UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
        
        [self.attrsArray addObject:attrs];
    }
}

//这个方法返回indexPath位置对应的cell布局属性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    CGFloat radius = 100;
    CGFloat OpointX = self.collectionView.frame.size.width *0.5;
    CGFloat OpointY = self.collectionView.frame.size.height *0.5;
  

        UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        
        attrs.size = CGSizeMake(75, 75);
    if (count ==1) {
            attrs.center = CGPointMake(OpointX, OpointY);
    }
        CGFloat angle = (2*M_PI / count)*indexPath.item;
        
        CGFloat centerX = OpointX + radius * sin(angle);
        CGFloat centerY = OpointY + radius * cos(angle);
        attrs.center = CGPointMake(centerX, centerY);
    
    return attrs;

}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    
    return self.attrsArray;
}

@end
